package com.grade.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.grade.common.utils.DateUtils;
import com.grade.system.domain.GradeItem;
import com.grade.system.domain.GradeTemplate;
import com.grade.system.mapper.GradeItemMapper;
import com.grade.system.mapper.GradeTemplateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.grade.system.mapper.GradeTypeMapper;
import com.grade.system.domain.GradeType;
import com.grade.system.service.IGradeTypeService;
import com.grade.common.core.text.Convert;

/**
 * 评分标准分类Service业务层处理
 * 
 * @author grade
 * @date 2021-10-17
 */
@Service
public class GradeTypeServiceImpl implements IGradeTypeService 
{
    @Autowired
    private GradeTypeMapper gradeTypeMapper;
    @Autowired
    private GradeItemMapper gradeItemMapper;
    @Autowired
    private GradeTemplateMapper gradeTemplateMapper;

    /**
     * 查询评分标准分类
     * 
     * @param typeId 评分标准分类主键
     * @return 评分标准分类
     */
    @Override
    public GradeType selectGradeTypeByTypeId(Long typeId)
    {
        return gradeTypeMapper.selectGradeTypeByTypeId(typeId);
    }

    /**
     * 查询评分标准分类列表
     * 
     * @param gradeType 评分标准分类
     * @return 评分标准分类
     */
    @Override
    public List<GradeType> selectGradeTypeList(GradeType gradeType)
    {
        return gradeTypeMapper.selectGradeTypeList(gradeType);
    }
    public List<GradeType> getGradeTypeOptionList(GradeType gradeType){
        List<GradeType> typeList = gradeTypeMapper.selectGradeTypeList(gradeType);
        return  assembleTypeOption(typeList);
    }


    private List<GradeType>assembleTypeOption(List<GradeType> typeList){
        if(typeList!=null && typeList.size()>0){
            Map<Long,Integer> layerMap = new HashMap<>();
            Map<Long,Long> parentMap = new HashMap<>();
            Map<Long,List<GradeType>> childrenListMap = new HashMap<>();
            for(GradeType gradeType: typeList){
                parentMap.put(gradeType.getTypeId(),gradeType.getParentId());
                List<GradeType> childrenList = childrenListMap.get(gradeType.getParentId());
                if(childrenList==null){
                    childrenList = new ArrayList<>();
                }
                childrenList.add(gradeType);
                childrenListMap.put(gradeType.getParentId(),childrenList);
            }
            for(GradeType gradeType: typeList){
                int layer = getLayer(gradeType.getTypeId(),parentMap);
                if(layer>0){
                    String typeName = gradeType.getTypeName();
                    for(int i=0;i<layer;i++){
                        typeName ="|__" + typeName;
                    }
                    gradeType.setTypeName(typeName);
                }
            }

            //深度优先遍历
            List<GradeType> sortedTypeList = new ArrayList<>();
            sortTypeList(0L,childrenListMap, sortedTypeList);

            return sortedTypeList;
        }
        return null;
    }
    //深度优先遍历
    private void sortTypeList (Long parentId,Map<Long,List<GradeType>> childrenListMap,List<GradeType> sortedTypeList){
        List<GradeType> childrenList = childrenListMap.get(parentId);
        if(childrenList!=null && !childrenList.isEmpty()){
            for(GradeType gt: childrenList){
                sortedTypeList.add(gt);
                sortTypeList (gt.getTypeId(),childrenListMap, sortedTypeList);
            }
        }
    }



    private int getLayer(Long typeId,Map<Long,Long> parentMap){
        int layer=0;
        Long parentId=parentMap.get(typeId);
        for(;;layer++){
            if(parentId==null || parentId.intValue()==0){
                break;
            }
            parentId=parentMap.get(parentId);
        }
        return layer;
    }


    public List<GradeType> selectGradeTypeAll(){
        return gradeTypeMapper.selectGradeTypeAll();
    }

    /**
     * 新增评分标准分类
     * 
     * @param gradeType 评分标准分类
     * @return 结果
     */
    @Override
    public int insertGradeType(GradeType gradeType)
    {
        gradeType.setCreateTime(DateUtils.getNowDate());
        return gradeTypeMapper.insertGradeType(gradeType);
    }

    /**
     * 修改评分标准分类
     * 
     * @param gradeType 评分标准分类
     * @return 结果
     */
    @Override
    public int updateGradeType(GradeType gradeType)
    {
        gradeType.setUpdateTime(DateUtils.getNowDate());

        GradeType originType = gradeTypeMapper.selectGradeTypeByTypeId(gradeType.getTypeId());
        if(originType==null){
            return 0;
        }

        //如果更新名称，就把模板中类型 名称中的全部更新
        if(!originType.getTypeName().equals(gradeType.getTypeName()) || originType.getTypeOrder() != gradeType.getTypeOrder())
        {
            //查询出路径
            GradeItem updateGradeItem = new GradeItem();
            updateGradeItem.setTemplateId(gradeType.getTemplateId());
            List<Long>childrenList = new ArrayList<>();
            int maxColumn = getMaxColumnAndChildrenList(gradeType.getTypeId(),childrenList);
            //加上本节点
            childrenList.add(gradeType.getTypeId());

            if (maxColumn == 1) {
                updateGradeItem.setFirstColumn(gradeType.getTypeName());
                updateGradeItem.setFirstOrder(gradeType.getTypeOrder());
            } else if (maxColumn == 2) {
                updateGradeItem.setSecondColumn(gradeType.getTypeName());
                updateGradeItem.setSecondOrder(gradeType.getTypeOrder());
            } else if (maxColumn == 3) {
                updateGradeItem.setThreeColumn(gradeType.getTypeName());
                updateGradeItem.setThreeOrder(gradeType.getTypeOrder());
            } else if (maxColumn == 4) {
                updateGradeItem.setFourColumn(gradeType.getTypeName());
                updateGradeItem.setFourOrder(gradeType.getTypeOrder());
            } else if (maxColumn == 5) {
                updateGradeItem.setFiveColumn(gradeType.getTypeName());
                updateGradeItem.setFiveOrder(gradeType.getTypeOrder());
            } else if (maxColumn == 6) {
                updateGradeItem.setSixColumn(gradeType.getTypeName());
                updateGradeItem.setSixOrder(gradeType.getTypeOrder());
            }
            gradeItemMapper.updateGradeTypeName(childrenList, updateGradeItem);

        }

        //如果更新计分类型，或者权重的分值更新了。就更新所有
        if(!originType.getScoreModel().equals(gradeType.getScoreModel()) || !IntegerEqual(originType.getWeight(),gradeType.getTypeOrder()))
        {
            //查询出路径
            GradeItem updateGradeItem = new GradeItem();
            updateGradeItem.setTemplateId(gradeType.getTemplateId());
            List<Long>childrenList = new ArrayList<>();
            int maxColumn = getMaxColumnAndChildrenList(gradeType.getTypeId(),childrenList);
            //加上本节点
            childrenList.add(gradeType.getTypeId());

            List<GradeItem> gradeItemList = gradeItemMapper.selectByTempalteIdTypeIds(childrenList, updateGradeItem);

            if(gradeItemList!=null &&gradeItemList.size()>0){
                List<GradeType> gradeTypeList = gradeTypeMapper.selectGradeTypeByTemplateId(gradeType.getTemplateId());
                Map<Long,GradeType>parentTypeMap = new HashMap<>();
                for(GradeType tempType: gradeTypeList){
                    if(tempType.getTypeId().intValue()==gradeType.getTypeId().intValue()){
                        tempType.setWeight(gradeType.getWeight());
                    }
                    parentTypeMap.put(tempType.getTypeId(),tempType);
                }
                for(GradeItem gradeItem: gradeItemList){
                    Long parentTypeId = gradeItem.getTypeId();
                    do{
                        GradeType parentType = parentTypeMap.get(parentTypeId);
                        if("2".equals(parentType.getScoreModel())){
                            Float weight = gradeItem.getWeight();
                            if(weight==null){
                                gradeItem.setWeight((float) parentType.getWeight());
                            }else {
                                gradeItem.setWeight(gradeItem.getWeight()* parentType.getWeight()/100);
                            }
                        }
                        parentTypeId = parentType.getParentId();
                    }while (parentTypeId>0);
                    gradeItemMapper.updateGradeWeightById(gradeItem);
                }
            }

        }

        return gradeTypeMapper.updateGradeType(gradeType);
    }

    /**
     * 修改评分标准分类
     *
     * @param gradeType 评分标准分类
     * @return 结果
     */
    @Override
    public String[] updateGradeType_New(GradeType gradeType)
    {
        String[] reVal=new String[2];
        gradeType.setUpdateTime(DateUtils.getNowDate());

        GradeType originType = gradeTypeMapper.selectGradeTypeByTypeId(gradeType.getTypeId());

        if(originType==null){
            reVal[0]="0";
            reVal[1]="未能获取到相应的评分类型数据";
            return reVal;
        }
        //判断选择的父分类是否为本级级子分类
        String child_TypeId=gradeTypeMapper.selectGradeTypeChilds(originType.getTypeId());
        if (!gradeType.getParentId().equals(originType.getParentId())) {
            if (child_TypeId!=null) {
                String[] child = child_TypeId.split(",");
                for(int i=0;i<child.length;i++){
                    if (gradeType.getParentId().toString().equals(child[i])){
                        reVal[0]="0";
                        reVal[1]="父分类不能选择该评分类型下的子类型";
                        return reVal;
                    }
                }
            }
        }

        gradeTypeMapper.updateGradeType(gradeType);

        //更新本分类及子分类下的评分细则权重、类型、排序号，以及该模版的层级
        List<GradeType> child_TypeIdList = gradeTypeMapper.selectGradeTypeChildsList(Convert.toStrArray(child_TypeId));
        for(int i=0;i<child_TypeIdList.size();i++){
            //更新类型、排序号及权重
            GradeItem gradeItem=new GradeItem();
            GradeType gradeType_Child=child_TypeIdList.get(i);
            assembleItemSixColumn_New(gradeItem,gradeType_Child.getTypeId(),gradeType_Child.getTemplateId());
            gradeItemMapper.updateGradeItemByTypeId(gradeItem);
        }

        //更新评分模版层级
        List<GradeItem> gradeItemList=gradeItemMapper.selectGradeItemByTemplateId(originType.getTemplateId());
        int maxLayer=0;
        int layer=0;
        for(int j=0;j<gradeItemList.size();j++){
            GradeItem gradeItem=gradeItemList.get(j);
            layer=0;
            if (gradeItem!=null){
                if (gradeItem.getFirstColumn()!=null && !gradeItem.getFirstColumn().equals("")){
                    layer=1;
                }
                if (gradeItem.getSecondColumn()!=null && !gradeItem.getSecondColumn().equals("")){
                    layer=2;
                }
                if (gradeItem.getThreeColumn()!=null && !gradeItem.getThreeColumn().equals("")){
                    layer=3;
                }
                if (gradeItem.getFourColumn()!=null && !gradeItem.getFourColumn().equals("")){
                    layer=4;
                }
                if (gradeItem.getFiveColumn()!=null && !gradeItem.getFiveColumn().equals("")){
                    layer=5;
                }
                if (gradeItem.getSixColumn()!=null && !gradeItem.getSixColumn().equals("")){
                    layer=6;
                }
            }
            if (layer>maxLayer){
                maxLayer=layer;
            }
        }

        GradeTemplate gradeTemplate = gradeTemplateMapper.selectGradeTemplateById(originType.getTemplateId());
        GradeTemplate template = new GradeTemplate();
        template.setId(originType.getTemplateId());
        template.setLayer(maxLayer);
        gradeTemplateMapper.updateGradeTemplate(template);

        reVal[0]="1";

        return reVal;
    }

    /**
     * 根据评分类型判断更改后的父类是否为改分类的子分类
     *
     * @param origin_ParentId 原父类ID
     * @param obj_ParentId 目标父类ID
     * @param templateId 模版ID
     * @return 结果
     */
    private void  isChild(Long origin_ParentId,Long obj_ParentId,Long templateId){
        List<GradeType> allTypeList = gradeTypeMapper.selectGradeTypeByTemplateId(templateId);
        Map<Long,Long> childrenParentMap= new HashMap<Long,Long>();
        //Map<Long,String> typeNameMap= new HashMap<Long,String>();
        Map<Long,GradeType> typeObjectMap= new HashMap<Long,GradeType>();

        for(GradeType gradeType_T: allTypeList){
            childrenParentMap.put(gradeType_T.getTypeId(),gradeType_T.getParentId());
            //typeNameMap.put(gradeType_T.getTypeId(),gradeType_T.getTypeName());
            typeObjectMap.put(gradeType_T.getTypeId(),gradeType_T);
        }
        Long parentId = origin_ParentId;
        List<GradeType> columonList = new ArrayList<GradeType>();
        int maxColumn = 0;
        do{
            maxColumn++;
            columonList.add(typeObjectMap.get(parentId));
            parentId = childrenParentMap.get(parentId);
        }while(parentId>0);
    }

    /**
     *获取本级及父类的评分类型
     *
     * @param gradeItem 更新评分细则的对象
     * @param typeId 评分类型ID
     * @param templateId 模版ID
     * @return 结果
     */
    private int assembleItemSixColumn_New(GradeItem gradeItem,Long typeId,Long templateId)
    {
        List<GradeType> allTypeList = gradeTypeMapper.selectGradeTypeByTemplateId(templateId);
        Map<Long,Long> childrenParentMap= new HashMap<Long,Long>();
        Map<Long,String> typeNameMap= new HashMap<Long,String>();
        Map<Long,GradeType> typeObjectMap= new HashMap<Long,GradeType>();

        for(GradeType gradeType_T: allTypeList){
            childrenParentMap.put(gradeType_T.getTypeId(),gradeType_T.getParentId());
            typeNameMap.put(gradeType_T.getTypeId(),gradeType_T.getTypeName());
            typeObjectMap.put(gradeType_T.getTypeId(),gradeType_T);
        }

        gradeItem.setTemplateId(templateId);
        return getMaxColumnAndSetTypeName(gradeItem,typeId,typeObjectMap,childrenParentMap);
    }


    /**
     *获得更新评分细则的类型、排序号、权重及层级值
     *
     * @param gradeItem 更新评分细则的对象
     * @param typeId 评分类型ID
     * @param typeObjectMap 本级及父类的评分类型对象
     * @param childrenParentMap 分类ID对应的父ID MAP对象
     * @return 结果
     */
    private int getMaxColumnAndSetTypeName(GradeItem gradeItem,Long typeId,Map<Long,GradeType> typeObjectMap,Map<Long,Long>childrenParentMap){
        int maxColumn = 0;
        List<GradeType> columonList = new ArrayList<GradeType>();
        Long parentId = typeId;
        gradeItem.setWeight(null);

        do{
            maxColumn++;
            columonList.add(typeObjectMap.get(parentId));

            gradeItem.setTypeId(typeId);
            //更新权重
            GradeType parentType = typeObjectMap.get(parentId);
            if ("2".equals(parentType.getScoreModel())) {
                Float weight = gradeItem.getWeight();
                if (weight == null) {
                    gradeItem.setWeight((float) parentType.getWeight());
                } else {
                    gradeItem.setWeight(gradeItem.getWeight() * parentType.getWeight() / 100);
                }
            }

            parentId = childrenParentMap.get(parentId);
        }while(parentId>0);

        for(int i=1;i<=maxColumn;i++){
            if(i==1){
                gradeItem.setFirstColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setFirstOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==2){
                gradeItem.setSecondColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setSecondOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==3){
                gradeItem.setThreeColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setThreeOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==4){
                gradeItem.setFourColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setFourOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==5){
                gradeItem.setFiveColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setFiveOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==6){
                gradeItem.setSixColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setSixOrder(columonList.get(maxColumn-i).getTypeOrder());
            }
        }

        return maxColumn;
    }

    private boolean IntegerEqual(Integer a,Integer b){
        if(a==null&&b==null) {
            return true;
        }
        if(a!=null &&b!=null && a.intValue()==b.intValue()){
            return true;
        }
        return false;
    }



    private int getMaxColumnAndChildrenList(Long typeId ,List<Long>childrenList){
        int maxColumn = 0;
        Long parentId = typeId;
        List<GradeType> allTypeList = gradeTypeMapper.selectGradeTypeAll();
        Map<Long,Long> childrenParentMap= new HashMap<Long,Long>();

        for(GradeType gradeType: allTypeList){
            childrenParentMap.put(gradeType.getTypeId(),gradeType.getParentId());
        }
        do{
            maxColumn++;
            parentId = childrenParentMap.get(parentId);
        }while(parentId>0);

        getChildrenTypeList(typeId,childrenList,childrenParentMap, allTypeList);
        return maxColumn;
    }

    //深度优先遍历
    private void getChildrenTypeList (Long parentId,List<Long>allChildrenList,Map<Long,Long> childrenParentMap,List<GradeType> allTypeList){
        if(parentId!=null){
            for(GradeType gt: allTypeList){
                if(gt.getParentId().intValue()==parentId.intValue()){
                    if(!allChildrenList.contains(gt.getTypeId())){
                        allChildrenList.add(gt.getTypeId());
                        getChildrenTypeList (gt.getTypeId(),allChildrenList, childrenParentMap, allTypeList);
                    }
                }
            }
        }
    }

    /**
     * 批量删除评分标准分类
     * 
     * @param typeIds 需要删除的评分标准分类主键
     * @return 结果
     */
    @Override
    public int deleteGradeTypeByTypeIds(String typeIds)
    {
        String[] typeIdArray=Convert.toStrArray(typeIds);
        for(int i=0;i<typeIdArray.length;i++) {
            Long typeId = Long.parseLong(typeIdArray[i]);
            GradeType gradeType=gradeTypeMapper.selectGradeTypeByTypeId(typeId);
            if (gradeType!=null) {
                //更新评分模版层级
                List<GradeItem> gradeItemList = gradeItemMapper.selectGradeItemByTemplateId(gradeType.getTemplateId());
                int maxLayer = 0;
                int layer = 0;
                for (int j = 0; j < gradeItemList.size(); j++) {
                    GradeItem gradeItem = gradeItemList.get(j);
                    layer = 0;
                    if (gradeItem != null) {
                        if (gradeItem.getFirstColumn() != null && !gradeItem.getFirstColumn().equals("")) {
                            layer = 1;
                        }
                        if (gradeItem.getSecondColumn() != null && !gradeItem.getSecondColumn().equals("")) {
                            layer = 2;
                        }
                        if (gradeItem.getThreeColumn() != null && !gradeItem.getThreeColumn().equals("")) {
                            layer = 3;
                        }
                        if (gradeItem.getFourColumn() != null && !gradeItem.getFourColumn().equals("")) {
                            layer = 4;
                        }
                        if (gradeItem.getFiveColumn() != null && !gradeItem.getFiveColumn().equals("")) {
                            layer = 5;
                        }
                        if (gradeItem.getSixColumn() != null && !gradeItem.getSixColumn().equals("")) {
                            layer = 6;
                        }
                    }
                    if (layer > maxLayer) {
                        maxLayer = layer;
                    }
                }

                GradeTemplate gradeTemplate = gradeTemplateMapper.selectGradeTemplateById(gradeType.getTemplateId());
                GradeTemplate template = new GradeTemplate();
                template.setId(gradeType.getTemplateId());
                template.setLayer(maxLayer);
                gradeTemplateMapper.updateGradeTemplate(template);
            }
        }

        return gradeTypeMapper.deleteGradeTypeByTypeIds(Convert.toStrArray(typeIds));
    }

    /**
     * 删除评分标准分类信息
     * 
     * @param typeId 评分标准分类主键
     * @return 结果
     */
    @Override
    public int deleteGradeTypeByTypeId(Long typeId)
    {
        return gradeTypeMapper.deleteGradeTypeByTypeId(typeId);
    }

    @Override
    public int countGradeTypeByTemplateIds(String[]  templateIds) {
        return gradeTypeMapper.countGradeTypeByTemplateIds(templateIds);
    }
}
